//路由鉴权
import router from '@/router'
//进度条
import Nprogress from 'nprogress'
//进度条样式
import 'nprogress/nprogress.css'
import useUserStore from "@/store/modules/user.ts";
import pinia from './store'
import {ElMessage} from "element-plus";
import setting from '/setting.ts'
//全局守卫

//进度条配置去除记载旋转动画
Nprogress.configure({showSpinner:false})
const userStore = useUserStore(pinia)
//全局前置守卫
router.beforeEach( async (to, from, next) => {
  document.title = `${setting.title} - ${to.meta.title}`
  //to: 将要访问哪个路由
  //from 从哪个路由来
  //next 是一个函数，表示放行
  Nprogress.start()

  const token = userStore.token;
  //仓库获取用户信息
  const username = userStore.username;

  if(token){
    if(to.path === '/login'){
      next({path:'/'})
    }else{
      if(username){
        next()
      }else{
        try { //请求获取用户信息
          await userStore.userInfo();
          next()
        } catch (e) {
          ElMessage.error(e.message)
          await userStore.userLogout();
          next({path:'/login',query:{redirect:to.path}})
        }

      }
    }
  }else{
    if(to.path === '/login'){
      next()
    }else{
      next({path:'/login',query:{redirect:to.path}})
    }
  }
})

// 全局后置守卫
router.afterEach((to, from) => {
  Nprogress.done()
})
